import {useState} from "react";
import {Button, Form, Input, message} from "antd";
import {UserOutlined, LockOutlined, CloseCircleOutlined} from "@ant-design/icons";
import {useTranslation} from "react-i18next";
import useAuthStore from "@/store/modules/auth";
import {LoginModel} from "@/api/interface/auth.ts";
import {useLocation, useNavigate} from "react-router-dom";
import {encrypt} from "@/utils/index.js";

const LoginForm = () => {
    const {t} = useTranslation()
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const navigate = useNavigate()
    const urlParams = new URLSearchParams(useLocation().search)
    const fromPath = urlParams.get("fromPath") || '/'
    const {login} = useAuthStore.getState()
    // 登录
    const onFinish = async (e: LoginModel) => {
        try {
            e.password = encrypt(e.password)
            setLoading(true);
            await login(e)
            message.success(t('login.loginSuccess'));
            navigate(fromPath)
        } finally {
            setLoading(false);
        }
    };

    const onFinishFailed = () => {
        setLoading(false);
    };

    return (
        <Form
            form={form}
            name="basic"
            labelCol={{span: 5}}
            initialValues={{remember: true}}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            size="large"
            autoComplete="off"
        >
            <Form.Item name="username" rules={[{required: true, message: t('login.pleaseInputUsername')}]}>
                <Input placeholder={`${t('login.username')}：admin`} prefix={<UserOutlined/>}/>
            </Form.Item>
            <Form.Item name="password" rules={[{required: true, message: t('login.pleaseInputPassword')}]}>
                <Input.Password autoComplete="new-password" placeholder={`${t('login.password')}：123456`}
                                prefix={<LockOutlined/>}/>
            </Form.Item>
            <Form.Item className="login-btn">
                <Button onClick={() => form.resetFields()} icon={<CloseCircleOutlined/>}>
                    {t('login.reset')}
                </Button>
                <Button type="primary" htmlType="submit" loading={loading} icon={<UserOutlined/>}>
                    {t('login.label')}
                </Button>
            </Form.Item>
        </Form>
    );
};
export default LoginForm
